/*
 *  Copyright 2019-2023 oyun
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.oyun.modules.medicine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oyun.modules.medicine.domain.*;
import com.oyun.modules.medicine.domain.vo.PharmaceuticalCompanyQueryCriteria;
import com.oyun.modules.medicine.mapper.CompanyHpMapper;
import com.oyun.modules.medicine.mapper.CompanyPictureMapper;
import com.oyun.modules.medicine.mapper.PharmaceuticalCompanyMapper;
import com.oyun.modules.medicine.service.PharmaceuticalCompanyService;
import com.oyun.segment.convert.itmd.IntermediateCodeUtils;
import com.oyun.utils.FileUtil;
import com.oyun.utils.PageResult;
import com.oyun.utils.PageUtil;
import com.oyun.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author oyun
 * @description 服务实现
 * @date 2024-04-29
 **/
@Service
@RequiredArgsConstructor
public class PharmaceuticalCompanyServiceImpl extends ServiceImpl<PharmaceuticalCompanyMapper, PharmaceuticalCompany> implements PharmaceuticalCompanyService {

    @Value("${file.windows.path}")
    private String path;

    private final CompanyPictureMapper companyPictureMapper;

    private final PharmaceuticalCompanyMapper pharmaceuticalCompanyMapper;

    private final CompanyHpMapper companyHpMapper;

    @Override
    public PageResult<PharmaceuticalCompany> queryAll(PharmaceuticalCompanyQueryCriteria criteria, Page<Object> page) {
        if (StringUtils.isNotEmpty(criteria.getName())) {
            criteria.setReplaceAll(IntermediateCodeUtils.mn2Code(criteria.getName()).replaceAll("-", " -"));
        }
        IPage<PharmaceuticalCompany> all = pharmaceuticalCompanyMapper.findAll(criteria, page);
        Acquire(all.getRecords());
        return PageUtil.toPage(all);


    }

    @Override
    public List<PharmaceuticalCompany> queryAll(PharmaceuticalCompanyQueryCriteria criteria) {
        return pharmaceuticalCompanyMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PharmaceuticalCompany resources) {
        convertCode(resources);
        save(resources);
        insertOrUpdate(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PharmaceuticalCompany resources) {
        PharmaceuticalCompany pharmaceuticalCompany = getById(resources.getId());
        pharmaceuticalCompany.copy(resources);
        convertCode(pharmaceuticalCompany);
        saveOrUpdate(pharmaceuticalCompany);
        //修改药企供应医院
        LambdaQueryWrapper<CompanyHp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(resources.getId() != null, CompanyHp::getCompanyId, resources.getId());
        List<CompanyHp> companyHps = companyHpMapper.selectList(wrapper);
        for (CompanyHp companyHp : companyHps) {
            companyHp.setStatus(0);
            companyHpMapper.updateById(companyHp);
        }
        insertOrUpdate(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
        LambdaQueryWrapper<CompanyPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CompanyPicture::getCompanyId, ids).eq(CompanyPicture::getStatus, 1);
        List<CompanyPicture> list = companyPictureMapper.selectList(wrapper);
        for (CompanyPicture companyPicture : list) {
            companyPicture.setStatus(0);
            companyPictureMapper.updateById(companyPicture);
        }
        LambdaQueryWrapper<CompanyHp> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(CompanyHp::getHospitalId, ids).eq(CompanyHp::getStatus, 1);
        List<CompanyHp> list1 = companyHpMapper.selectList(wrapper1);
        for (CompanyHp companyHp : list1) {
            companyHp.setStatus(0);
            companyHpMapper.updateById(companyHp);
        }


    }

    @Override
    public void download(List<PharmaceuticalCompany> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PharmaceuticalCompany pharmaceuticalCompany : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("企业性质(字典)", pharmaceuticalCompany.getNature());
            map.put("旗县区的地区代码", pharmaceuticalCompany.getAreaCode());
            map.put("药企名称", pharmaceuticalCompany.getMnName());
            map.put(" mnNameCode", pharmaceuticalCompany.getMnNameCode());
            map.put(" zhName", pharmaceuticalCompany.getZhName());
            map.put("企业所在地", pharmaceuticalCompany.getMnLocation());
            map.put(" mnLocationCode", pharmaceuticalCompany.getMnLocationCode());
            map.put(" zhLocation", pharmaceuticalCompany.getZhLocation());
            map.put("联系方式", pharmaceuticalCompany.getContactInformation());
            map.put("法人代表", pharmaceuticalCompany.getMnLegalPerson());
            map.put(" mnLegalPersonCode", pharmaceuticalCompany.getMnLegalPersonCode());
            map.put(" zhLegalPerson", pharmaceuticalCompany.getZhLegalPerson());
            map.put("蒙语研发药物", pharmaceuticalCompany.getMnMedicine());
            map.put(" mnMedicineCode", pharmaceuticalCompany.getMnMedicineCode());
            map.put(" zhMedicine", pharmaceuticalCompany.getZhMedicine());
            map.put("企业业务方向蒙古文", pharmaceuticalCompany.getMnDirection());
            map.put(" mnDirectionCode", pharmaceuticalCompany.getMnDirectionCode());
            map.put(" zhDirection", pharmaceuticalCompany.getZhDirection());
            map.put("占地面积", pharmaceuticalCompany.getFloorSpace());
            map.put("占地面积单位（字典）", pharmaceuticalCompany.getFloorSpaceUnit());
            map.put("简介蒙古文", pharmaceuticalCompany.getMnIntro());
            map.put(" mnIntroCode", pharmaceuticalCompany.getMnIntroCode());
            map.put(" zhIntro", pharmaceuticalCompany.getZhIntro());
            map.put(" createBy", pharmaceuticalCompany.getCreateBy());
            map.put(" createTime", pharmaceuticalCompany.getCreateTime());
            map.put(" updateBy", pharmaceuticalCompany.getUpdateBy());
            map.put(" updateTime", pharmaceuticalCompany.getUpdateTime());
            map.put(" status", pharmaceuticalCompany.getStatus());
            map.put("备注", pharmaceuticalCompany.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String uploadOrUpdate(MultipartFile file, HttpServletRequest request, Long id) {
        File filee = new File(path + "/company");
        if (!filee.exists()) {//不存在
            filee.mkdirs();
        }
        String filename = file.getOriginalFilename();//获取文件名称带后缀名
        String uid = UUID.randomUUID().toString();//生成32为uuid值
        String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
        String newFile = uid + suffix;//拼接新的文件名称
        File file1 = new File(filee + "/" + newFile);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        LambdaQueryWrapper<CompanyPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null, CompanyPicture::getCompanyId, id).eq(CompanyPicture::getStatus, 1);
        CompanyPicture picture = companyPictureMapper.selectOne(wrapper);
        if (picture == null) {
            //新增
            CompanyPicture companyPicture = new CompanyPicture();
            companyPicture.setCompanyId(id);
            companyPicture.setPathImage("/company/" + newFile);
            companyPicture.setStatus(1);
            companyPictureMapper.insert(companyPicture);
        } else {
            //修改
            picture.setPathImage("/company/" + newFile);
            picture.setStatus(1);
            companyPictureMapper.updateById(picture);
        }
        return newFile;
    }

    @Override
    public Object getByName(String name) {
        String replaceAll = IntermediateCodeUtils.mn2Code(name).replaceAll("-", " -");
        LambdaQueryWrapper<PharmaceuticalCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(PharmaceuticalCompany::getZhName, name).or().like(PharmaceuticalCompany::getMnNameCode, replaceAll);
        List<PharmaceuticalCompany> companyList = pharmaceuticalCompanyMapper.selectList(wrapper);
        Acquire(companyList);
        return companyList;
    }


    private void insertOrUpdate(PharmaceuticalCompany resources) {
        for (Long hpid : resources.getHpIds()) {
            CompanyHp companyHp = new CompanyHp();
            companyHp.setCompanyId(resources.getId());
            companyHp.setHospitalId(hpid);
            companyHp.setStatus(1);
            companyHpMapper.insert(companyHp);
        }
    }

    private void convertCode(PharmaceuticalCompany pharmaceuticalCompany) {
        pharmaceuticalCompany.setMnNameCode(IntermediateCodeUtils.mn2Code(pharmaceuticalCompany.getMnName()).replaceAll("-", " -"));
        pharmaceuticalCompany.setMnLocationCode(IntermediateCodeUtils.mn2Code(pharmaceuticalCompany.getMnLocation()).replaceAll("-", " -"));
        pharmaceuticalCompany.setMnLegalPersonCode(IntermediateCodeUtils.mn2Code(pharmaceuticalCompany.getMnLegalPerson()).replaceAll("-", " -"));
        pharmaceuticalCompany.setMnMedicineCode(IntermediateCodeUtils.mn2Code(pharmaceuticalCompany.getMnMedicine()).replaceAll("-", " -"));
        pharmaceuticalCompany.setMnDirectionCode(IntermediateCodeUtils.mn2Code(pharmaceuticalCompany.getMnDirection()).replaceAll("-", " -"));
        pharmaceuticalCompany.setMnIntroCode(IntermediateCodeUtils.mn2Code(pharmaceuticalCompany.getMnIntro()).replaceAll("-", " -"));

    }

    private void Acquire(List<PharmaceuticalCompany> list) {
        for (PharmaceuticalCompany company : list) {
            LambdaQueryWrapper<CompanyPicture> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(company.getId() != null, CompanyPicture::getCompanyId, company.getId());
            List<CompanyPicture> companyPictures = companyPictureMapper.selectList(wrapper);
            if (!companyPictures.isEmpty()) {
                company.setImage(companyPictures.get(0).getPathImage());
            }
            LambdaQueryWrapper<CompanyHp> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(company.getId() != null, CompanyHp::getCompanyId, company.getId()).eq(CompanyHp::getStatus, 1);
            List<CompanyHp> companyHps = companyHpMapper.selectList(wrapper1);
            List<Long> collect = companyHps.stream().map(CompanyHp::getHospitalId).collect(Collectors.toList());
            company.setHpIds(collect);
        }
    }

}
